#!/bin/bash

set -e

CUR_DIR=$PWD
SRC_DIR=$PWD
cmd=$1
service_name=$2

export GOPROXY=https://goproxy.io
export GOPATH=/usr/local/go/goPath
export GOBIN=$GOPATH/bin

PKG_LIST=$(go list ./... | grep -v /vendor/)
LINT_VER=v0.0.0-20190409202823-959b441ac422

# Code coverage generation
function coverage_test() {
    COVERAGE_DIR="${COVERAGE_DIR:-coverage}"
    mkdir -p "$COVERAGE_DIR"
    for package in ${PKG_LIST}; do
        go test -covermode=count -coverprofile "${COVERAGE_DIR}/${package##*/}.temp" "$package"
    done
    echo 'mode: count' >"${COVERAGE_DIR}"/coverage.cov
    tail -q -n +2 "${COVERAGE_DIR}"/*.temp >>"${COVERAGE_DIR}"/coverage.cov
    go tool cover -func="${COVERAGE_DIR}"/coverage.cov
    if [ "$1" == "html" ]; then
        go tool cover -html="${COVERAGE_DIR}"/coverage.cov -o coverage.html
    fi
    rm -rf "$COVERAGE_DIR"
}

# Backup file function
function backup_file() {
    srv_name=$1
    src_dir="/app/bird-airport/$srv_name"

    if [ -d "$src_dir" ]; then
        src_file="$src_dir/$srv_name"
        if [ -e "$src_file" ]; then
            sudo mv "$src_file" "${src_file}.bak"
        else
            echo "Source file for $srv_name does not exist. No backup performed."
        fi
    else
        echo "Directory $src_dir does not exist. No backup performed."
    fi
}

# Build and move function
function build_and_move() {
    srv_name=$1

    # Execute backup
    $0 bak "$srv_name"
    echo "work dir is $PWD"
    go mod tidy
    echo "root go mod tidy success"
    # Enter directory and build
    cd "$SRC_DIR/app/$srv_name/cmd/server"
    go mod tidy
    echo "$srv_name go mod tidy success"
    go build -o "$service_name"
    echo "build $service_name success"
    # Move built executable file
    sudo mkdir -p "/app/bird-airport/$service_name"
    mv "./$service_name" "/app/bird-airport/$service_name/"
    echo "build success"
}

case $cmd in
lint)
    $0 dep && $GOBIN/golint -set_exit_status ${PKG_LIST}
    ;;
test)
    go test -short ${PKG_LIST}
    ;;
race)
    $0 dep && go test -race -short ${PKG_LIST}
    ;;
coverage)
    coverage_test
    ;;
coverhtml)
    coverage_test html
    ;;
dep)
    go get -v golang.org/x/lint@$LINT_VER && cd $GOPATH/pkg/mod/golang.org/x/lint@$LINT_VER/ && go install ./... && cd $CUR_DIR
    ;;
bak)
    backup_file "$service_name"
    ;;
build)
    build_and_move "$service_name"
    ;;
deploy)
    supervisorctl restart "$service_name"
    ;;
*)
    echo "Unknown command: $cmd"
    exit 1
    ;;
esac

cd $CUR_DIR
